package com.gblfy.qywxin.service;

import com.gblfy.qywxin.config.QywxInnerConfig;
import com.gblfy.qywxin.utils.RestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class QywxInnerMiniService {

    private static final Logger logger = LoggerFactory.getLogger(QywxInnerMiniService.class);

    @Value("${qywx.mini.agentSecret}")
    private String AGENT_SECRET;

    public Map getOauthUser(String corpId, String code) {
        // 1.通过corpId获取AccessToken
        String accessToken = getAccessToken(corpId);

        String getOauthUrl = String.format(QywxInnerConfig.MINI_OAUTH_USER_URL, accessToken, code);
        Map response = RestUtils.get(getOauthUrl);
        if (response.containsKey("errcode") && (Integer) response.get("errcode") != 0) {
            logger.error(response.toString());
            return response;
        }
        System.out.println("response->" + response);

        //  目前已经获取到userid了
        // return response;
        //根据用户UserId->获取通讯录用户详情get
        String userId = (String) response.get("userid");
        String url = String.format(QywxInnerConfig.USER_DETAIL_URL, accessToken, userId);
        Map detaiResponse = RestUtils.get(url);

        //获取错误日志
        if (detaiResponse.containsKey("errcode") && (Integer) detaiResponse.get("errcode") != 0) {
            logger.error(detaiResponse.toString());
        }
        return detaiResponse;
    }

    /**
     * 通过corpId获取AccessToken
     *
     * @param corpId 企业ID
     * @return
     */
    public String getAccessToken(String corpId) {
        String result = "";

        String accessTokenUrl = String.format(QywxInnerConfig.MINI_ACCESS_TOKEN_URL, corpId, AGENT_SECRET);
        Map response = RestUtils.get(accessTokenUrl);

        //获取错误日志
        if (response.containsKey("errcode") && (Integer) response.get("errcode") != 0) {
            logger.error(response.toString());
        } else {
            result = (String) response.get("access_token");
        }
        return result;
    }
}
